import React, { useEffect, useState } from "react";
import "../../scss/hwb_css/management.scss"
import { stageAPI, questionAPI2, academyAPI,stageAPI_add,stageAPI_del,stageAPI_edit,stageAPI_echo } from "./hwb_API";
import { Input, Button } from "antd";
import { Divider, Table, Select } from "antd";
import { Pagination } from "tdesign-react";
import { Form, Modal, Radio } from "antd";
import { useNavigate } from "react-router-dom";

function Management() {
  const navigate = useNavigate();
  const [stage_list, setStage_list] = useState([]);
  const [question_list, setQuestion_list] = useState([]);
  const [academy_list, setAcademy_list] = useState([]);

  // 题库表
  const getStage = async () => {
    let {
      data: { stage_list, total },
    } = await stageAPI({ value, page, pagesize });
    setStage_list(stage_list);
    setTotal(total);  
  };
  //试题表
  const getQuestion = async () => {
    let {
      data: { question_list },
    } = await questionAPI2();
    setQuestion_list(question_list);
  };
  //学院表
  const getAcademy = async () => {
    let {
      data: { academy_list },
    } = await academyAPI();
    setAcademy_list(academy_list);
  };
  //搜索
  const search = () => {
    getStage();
    setValue("");
  };
  //重置
  const reset = () => {
    getStage();
    setValue(""); //清空搜索框
  };
  //搜索
  const [value, setValue] = useState("");

  //渲染
  const [columns, setColumns] = useState([
    {
      title: "题库名称",
      dataIndex: "name",
    },
    {
      title: "创建人",
      dataIndex: "creator",
    },
    {
      title: "试题总量",
      dataIndex: "zongliang",
    },
    {
      title: "单选题",
      dataIndex: "danxuan",
    },
    {
      title: "多选题",
      dataIndex: "duoxuan",
    },
    {
      title: "判断题",
      dataIndex: "panduan",
    },
    {
      title: "简答题",
      dataIndex: "jianda",
    },
    {
      title: "操作",
      dataIndex: "caozuo",
    },
  ]);

  //分页
  const [page, setPage] = useState(1);
  const [pagesize, setPagesize] = useState(2);
  const [total, setTotal] = useState(0);
  const onChange = (pageNumber) => {
    setPage(pageNumber.current);
  };
  const onPageSizeChange = (num) => {
    setPagesize(num);
  };

  //弹出
  const [text, setText] = useState("");
  const [form] = Form.useForm();
  const [fid, setFid] = useState("");
  const [sid,setSid] = useState("");
  const [formValues, setFormValues] = useState({});
  const [open, setOpen] = useState(false);

  //添加-修改
  const onCreate =async (values) => {
    setFormValues(values);
    if(text === "新增题库"){
      values.creator=localStorage.getItem('_id') || '66d02419a5ff158b2695e15f'
      let {data:{msg}} = await stageAPI_add(values);
      getStage();
      setOpen(false);
    }else{
      values.id=fid;
      values.creator=localStorage.getItem('_id') || '66d02419a5ff158b2695e15f'
      let {data:{msg}} = await stageAPI_edit(values);
      getStage();
      setOpen(false);
    }
  };

  //回显
  let echo=async(id)=>{
    setFid(id);
    setText("编辑题库");
    setOpen(true);
    let {data:{stage}} = await stageAPI_echo({id});
    form.setFieldsValue(stage);
  }
  //删除
  let del=async(id)=>{
    //选择是否删除
    Modal.confirm({
      title: "提示",
      content: "确定要删除吗？",
      onOk: async () => {
        await stageAPI_del({id});
        getStage();
      }
    })
  }

  useEffect(() => {
    getStage();
    getQuestion();
    getAcademy();
  }, [page, pagesize]);
  return (
    <div>
      <div className="management">
        <div className="header">
          <p className="p1">题库管理</p>
          {/* <hr /> */}
          <div className="head1">
            <div className="nav1">
              <p>题库名称：</p>
              <Input
                placeholder="请输入"
                onChange={(value) => {
                  setValue(value.target.value);
                }}
                value={value}
              />
            </div>
            <div className="nav2">
              <Button type="primary" onClick={search}>
                查询
              </Button>
              <Button onClick={reset}>重置</Button>
            </div>
          </div>

          <div className="head2">
            <Button
              type="primary"
              onClick={() => {
                setOpen(true);
                setText("新增题库");
              }}
            >
              新增题库
            </Button>
          </div>
        </div>
        <div className="content">
          {/* <Divider>Middle size table</Divider> */}
          <Table
            columns={columns}
            dataSource={stage_list.map((item) => ({
              key: item._id,
              name: <p onClick={()=>{navigate('/home/increased?id='+item._id)}}>{item.name}</p>,
              creator: item.creator.name,  
              zongliang: question_list.filter(
                (item2) => item2.belong === item._id
              ).length,
              danxuan: question_list.filter(
                (item2) => item2.belong === item._id && item2.cate === 1
              ).length,
              duoxuan: question_list.filter(
                (item2) => item2.belong === item._id && item2.cate === 2
              ).length,
              panduan: question_list.filter(
                (item2) => item2.belong === item._id && item2.cate === 3
              ).length,
              jianda: question_list.filter(
                (item2) => item2.belong === item._id && item2.cate === 4
              ).length,
              caozuo: 
                <div>
                  <Button
                    type="primary"
                    size="middle"
                    onClick={()=>{echo(item._id)}}
                  >
                    编辑
                  </Button>
                  <Button
                    type="primary"
                    size="middle"
                    onClick={() => {
                      del(item._id);
                    }}
                  >
                    删除
                  </Button>
                </div>,
            }))}
            size="middle"
            pagination={false}
          />
        </div>
        <div className="foot">
          <Pagination
            style={{ width: "600px", margin: "0 auto" }}
            showJumper
            total={total}
            current={page}
            pageSize={pagesize}
            onChange={onChange}
            onPageSizeChange={onPageSizeChange}
            pageSizeOptions={[
              { label: "1条/页", value: 1 },
              { label: "2条/页", value: 2 },
              { label: "3条/页", value: 3 },
              { label: "4条/页", value: 4 },
              { label: "5条/页", value: 5 },
            ]}
          />
        </div>
        <div className="tan">
          <Modal
            open={open}
            title={text}
            okText="确定"
            cancelText="取消"
            okButtonProps={{
              autoFocus: true,
              htmlType: "submit",
            }}
            onCancel={() => setOpen(false)}
            destroyOnClose
            modalRender={(dom) => (
              <Form
                layout="vertical"
                form={form}
                name="form_in_modal"
                initialValues={{
                  modifier: "public",
                }}
                clearOnDestroy
                onFinish={(values) => onCreate(values)}
              >
                {dom}
              </Form>
            )}
          >
            <Form.Item name="name" label="题库名称：">
              <Input type="text"/>
            </Form.Item>
            <Form.Item name="academy" label="所属学院：">
              <Select>
                {academy_list.map((item) => (
                  <Select.Option key={item._id} value={item._id}>
                    {item.name}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </Modal>
        </div>
      </div>
    </div>
  );
}

export default Management;
